﻿using Common.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using Serilog.Exceptions;
using Serilog.Formatting.Compact;
using Serilog.Formatting.Elasticsearch;
using Serilog.Sinks.Elasticsearch;
using Serilog.Sinks.SystemConsole.Themes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.SerilogService
{
    public static class SerilogExtension
    {
        const string OUTPUT_TEMPLATE = "[{Timestamp:yyyy-MM-dd HH:mm:ss}{Level:u3}] " +
            "ThreadId:{ThreadId},env:{EnvironmentUserName}{NewLine}" +
            "{Message:lj}{NewLine}{Exception}";
        static SerilogExtension()
        {
            Log.Logger = RegistLogger();
        }
        public static ILogger RegistLogger()
        {
            return new LoggerConfiguration()
                .ReadFrom.Configuration(configuration: ConfigurationHelper.GetIConfiguration())
                .CreateLogger();
            //return new LoggerConfiguration()
            //    //配置日志最小输出的级别为：debug
            //    .MinimumLevel.Information()
            //    //如果是Microsoft的日志，最小记录等级为info
            //    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            //    .Enrich.FromLogContext()
            //    .Enrich.WithProcessId()
            //    .Enrich.WithThreadId()
            //    .Enrich.WithExceptionDetails()
            //    .Enrich.WithEnvironmentUserName()
            //    //输出到控制台
            //    .WriteTo.Console(new ElasticsearchJsonFormatter())
            //    //将日志保存到文件中（两个参数分别是日志的路径和生成日志文件的频次，当前是一天一个文件）
            //    .WriteTo.File(Path.Combine("logs", @"log.txt"), restrictedToMinimumLevel: LogEventLevel.Warning, rollingInterval: RollingInterval.Day)
            //    .WriteTo.Elasticsearch()
            //    .CreateLogger();
        }

        public static IHostBuilder UseSerilogs(this IHostBuilder builder)
        {
            return builder.UseSerilog();
        }

        public static void UseSerilogRequestLoggings(this IApplicationBuilder app)
        {
            app.UseSerilogRequestLogging();
        }
    }
}
